package com.lagou.springboot.controller;

import com.lagou.springboot.pojo.Article;
import com.lagou.springboot.pojo.Page;
import com.lagou.springboot.pojo.PageResult;
import com.lagou.springboot.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;


@Controller
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;

    @RequestMapping("/all/{page}")
    public String findAllByPage(@PathVariable(name = "page") Integer pageNum, Model model) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageResult<Article> articlePageResult = articleService.findAllArticles(pageNum);

        // 设置分页
        Page page = new Page();
        int total = articlePageResult.getTotal();
        // 上一页
        if (pageNum == 1) {
            page.setPreviousPage(1);
        } else {
            page.setPreviousPage(pageNum - 1);
        }
        // 下一页
        if (pageNum == total) {
            page.setNextPage(total);
        } else {
            page.setNextPage(pageNum + 1);
        }
        // 首页和末页
        page.setFirstPage(1);
        page.setLastPage(total);
        model.addAttribute("page", page);

        // 设置结果
        model.addAttribute("article", articlePageResult.getRows());
        return "client/index";
    }

    @RequestMapping("/all")
    public String findAll() {
        return "forward:/article/all/1";
    }
}
